<template>
	<div class="map">
		<div id="container" />
		<div>
			<select v-model="range" @change="rangeChange">
				<option :value="'province'">省级</option>
				<option :value="'city'">市级</option>
				<option :value="'area'">区级</option>
			</select>
			<select v-model="style" @change="styleChange">
				<option v-for="item in styleOptions" :key="item.value"  :value="item.value">
					{{ item.label }}
				</option>
			</select>
		</div>
	</div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import data from './data.js';

let instance = null;

export default {
	data() {
		return {
    	// map:null, // 此处不声明 map 对象，可以直接使用 this.map 赋值或者采用非响应式的普通对象来存储。
			zoom: 4.8,
			range: 'province',
			style: 'normal',
			styleOptions: [
				{ label: '标准', value: 'normal' },
				{ label: '幻影黑', value: 'dark' },
				{ label: '月光银', value: 'light' },
				{ label: '远山黛', value: 'whitesmoke' },
				{ label: '草色青', value: 'fresh' },
				{ label: '雅士灰', value: 'grey' },
				{ label: '涂鸦', value: 'graffiti' },
				{ label: '马卡龙', value: 'macaron' },
				{ label: '靛青蓝', value: 'blue' },
				{ label: '极夜蓝', value: 'darkblue' },
				{ label: '酱籽', value: 'wine' },
			]
		}
	},
	async mounted() {
		await this.initMap();
		this.drawAreaMap();
	},
	methods: {
		/** @name 初始化地图 **/
		initMap() {
			return new Promise(resolve => {
				window._AMapSecurityConfig = {
					securityJsCode: '',
				}
				AMapLoader.load({
					key: '', // 申请好的Web端开发者Key, 首次调用 load 时必填
					version: '2.0',      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
					plugins: [
						'AMap.DistrictSearch'
					],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
				}).then((AMap)=>{
					this.map = new AMap.Map('container', {
						center: [110.17293, 35.20173],
						zoom: this.zoom, // 缩放级别
						mapStyle: 'amap://styles/' + this.style,
					});
					this.map.on('complete', () => {
						resolve();
					});
				}).catch(e=>{
					console.log(e);
				})
			})
		},
		/** @name 显示范围改变 **/
		rangeChange() {
			this.drawAreaMap();
		},
		/** @name 主题风格切换 **/
		async styleChange() {
			await this.initMap();
			this.drawAreaMap();
		},
		/** @name 绘制区域地图 **/
		async drawAreaMap() {
			const allAdCode = await this.getAllAdCode();
			// 将树形转换成对象形式
			const allAdCodeMap = this.transformTree(allAdCode);
			// 获取行政编码
			const adcode = []
			data.forEach(address => {
				if (this.range === 'province') {
					adcode.push(allAdCodeMap[address.province]?.adcode || '');
				}
				if (this.range === 'city') {
					// 处理直辖市
					const directCity = [
						{ label: '北京市', value: '110000' },
						{ label: '天津市', value: '120000' },
						{ label: '重庆市', value: '500000' },
						{ label: '上海市', value: '310000' },
						{ label: '香港特别行政区', value: '810000' },
					];
					const target = directCity.find(item => item.label === address.province);
					if (target) {
						adcode.push(target.value);
					} else {
						adcode.push(allAdCodeMap[address.city]?.adcode || '');
					}
				}
				if (this.range === 'area') {
					adcode.push(allAdCodeMap[address.area]?.adcode || '');
				}
			});
			instance && instance.setMap(null);
			const depth = {
				province: 0,
				city: 1,
				area: 2,
			};
			instance = new window.AMap.DistrictLayer.Province({
				adcode,
				depth: depth[this.range],
				styles: {
					'fill': fillParams => {
						const r = Math.floor(Math.random() * 255);
						const g = Math.floor(Math.random() * 255);
						const b = Math.floor(Math.random() * 255);
						const color = `rgba(${r}, ${g}, ${b}, 0.8)`;
						return adcode.includes(`${fillParams.adcode}`) ? color : undefined;
					},
				},
			});
			instance.setMap(this.map);
		},
		/** @name 将树形的行政编码转成对象形式 **/
		transformTree(allAdCode) {
			let allAdCodeMap = {};
			if (this.range === 'province') {
				allAdCodeMap = allAdCode.districtList.reduce((result, province) => {
					result[province.name] = province;
					return result;
				}, {});
			}
			if (this.range === 'city') {
				data.forEach(address => {
					const province = allAdCode.districtList.find(
						item => item.name === address.province,
					);
					if (province && province.districtList) { // 注意台湾省数据没有districtList
						const cityMap = province.districtList.reduce((result, city) => {
							result[city.name] = city;
							return result;
						}, {});
						allAdCodeMap = {
							...allAdCodeMap,
							...cityMap,
						}
					}
				})
			}
			if (this.range === 'area') {
        data.forEach(address => {
					const province = allAdCode.districtList.find(
						item => item.name === address.province,
					);
					if (province && province.districtList) {
						const city = province.districtList.find(
							item => item.name === address.city,
						);
						if (city && city.districtList) {
							const areaMap = city.districtList.reduce((result, area) => {
								result[area.name] = area;
								return result;
							}, {})
							allAdCodeMap = {
								...allAdCodeMap,
								...areaMap,
							}
						}
					}
				});
      }
			return allAdCodeMap;
		},
		/** @name 获取所有区域板块的行政编码 **/
		getAllAdCode() {
			return new Promise(resolve => {
				const searchInstance = new window.AMap.DistrictSearch({
					subdistrict: 3,
					showbiz: false,
				});
				searchInstance.search('中国', (status, result) => {
					if (status === 'complete') {
						resolve(result.districtList[0]);
					}
				});
			});
		}
	}
}
</script>

<style scoped>
.map {
	width: 740px;
	height: 500px;
	position: relative;
	display: flex;
	justify-content: flex-start;
	align-items: flex-start;
}
#container {
	width: 100%;
	height: 100%;
	margin-right: 10px;
}
</style>
